# AI 智能客服业务助理 PowerShell 停止脚本
# Windows PowerShell 7.5 兼容版本

param(
    [switch]$Force,
    [switch]$Clean,
    [switch]$Verbose
)

# 设置错误处理
$ErrorActionPreference = "Continue"
$VerbosePreference = if ($Verbose) { "Continue" } else { "SilentlyContinue" }

# 颜色输出函数
function Write-ColorOutput {
    param(
        [string]$Message,
        [string]$Color = "White"
    )
    Write-Host $Message -ForegroundColor $Color
}

function Write-Success {
    param([string]$Message)
    Write-ColorOutput "✅ $Message" "Green"
}

function Write-Error {
    param([string]$Message)
    Write-ColorOutput "❌ $Message" "Red"
}

function Write-Warning {
    param([string]$Message)
    Write-ColorOutput "⚠️  $Message" "Yellow"
}

function Write-Info {
    param([string]$Message)
    Write-ColorOutput "ℹ️  $Message" "Cyan"
}

# 获取脚本所在目录
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $ScriptDir

Write-ColorOutput "🛑 停止 AI 智能客服业务助理..." "Magenta"

# 停止进程的函数
function Stop-ServiceProcess {
    param(
        [string]$ProcessName,
        [string]$DisplayName,
        [int[]]$ExcludePids = @()
    )

    Write-Info "查找 $DisplayName 进程..."

    $processes = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue | Where-Object {
        $_.Id -notin $ExcludePids
    }

    if ($processes) {
        foreach ($process in $processes) {
            try {
                Write-Info "停止 $DisplayName 进程 (PID: $($process.Id))"
                Stop-Process -Id $process.Id -Force:$Force -ErrorAction Stop
                Write-Success "$DisplayName 进程已停止"
            } catch {
                Write-Warning "无法停止 $DisplayName 进程 (PID: $($process.Id)): $_"
            }
        }
    } else {
        Write-Info "未找到运行中的 $DisplayName 进程"
    }
}

# 停止端口占用的进程
function Stop-PortProcess {
    param(
        [int]$Port,
        [string]$ServiceName
    )

    Write-Info "查找占用端口 $Port 的进程..."

    try {
        # 使用 netstat 查找端口占用
        $netstat = netstat -ano | findstr ":$Port "

        if ($netstat) {
            $lines = $netstat -split "`n"
            foreach ($line in $lines) {
                if ($line -match ":$Port\s.*LISTENING\s+(\d+)") {
                    $pid = $matches[1]
                    try {
                        $process = Get-Process -Id $pid -ErrorAction SilentlyContinue
                        if ($process) {
                            Write-Info "停止 $ServiceName 进程 (PID: $pid, 进程名: $($process.ProcessName))"
                            Stop-Process -Id $pid -Force:$Force -ErrorAction Stop
                            Write-Success "$ServiceName 服务已停止"
                        } else {
                            Write-Warning "进程 PID $pid 不存在或已停止"
                        }
                    } catch {
                        Write-Warning "无法停止 $ServiceName 进程 (PID: $pid): $_"
                    }
                }
            }
        } else {
            Write-Info "端口 $Port 未被占用"
        }
    } catch {
        Write-Warning "检查端口 $Port 时出错: $_"
    }
}

# 停止 Ollama 服务
function Stop-OllamaService {
    Write-Info "停止 Ollama 服务..."

    # 查找 ollama 进程
    Stop-ServiceProcess "ollama" "Ollama"

    # 停止可能的 ollama 子进程
    $ollamaProcesses = Get-Process | Where-Object {
        $_.ProcessName -like "*ollama*" -or $_.MainWindowTitle -like "*ollama*"
    }

    foreach ($process in $ollamaProcesses) {
        try {
            Write-Info "停止 Ollama 相关进程 (PID: $($process.Id), 进程名: $($process.ProcessName))"
            Stop-Process -Id $process.Id -Force:$Force -ErrorAction Stop
        } catch {
            Write-Warning "无法停止进程 PID $($process.Id): $_"
        }
    }
}

# 清理函数
function Clean-Up {
    if (-not $Clean) {
        return
    }

    Write-Info "清理临时文件和缓存..."

    # 清理 Python 缓存
    $pythonCacheDirs = Get-ChildItem -Path $ScriptDir -Directory -Recurse -Include "__pycache__" -ErrorAction SilentlyContinue
    foreach ($dir in $pythonCacheDirs) {
        try {
            Remove-Item $dir.FullName -Recurse -Force
            Write-Verbose "已删除: $($dir.FullName)"
        } catch {
            Write-Warning "无法删除 $($dir.FullName): $_"
        }
    }

    # 清理 Node.js 缓存
    $nodeModulesDirs = Get-ChildItem -Path $ScriptDir -Directory -Recurse -Include "node_modules" -ErrorAction SilentlyContinue
    foreach ($dir in $nodeModulesDirs) {
        try {
            Remove-Item $dir.FullName -Recurse -Force
            Write-Verbose "已删除: $($dir.FullName)"
        } catch {
            Write-Warning "无法删除 $($dir.FullName): $_"
        }
    }

    # 清理日志文件
    $logFiles = Get-ChildItem -Path $ScriptDir -File -Recurse -Include "*.log" -ErrorAction SilentlyContinue
    foreach ($file in $logFiles) {
        try {
            Remove-Item $file.FullName -Force
            Write-Verbose "已删除: $($file.FullName)"
        } catch {
            Write-Warning "无法删除 $($file.FullName): $_"
        }
    }

    Write-Success "清理完成"
}

# 停止 Docker 容器（如果使用 Docker）
function Stop-DockerServices {
    Write-Info "检查并停止 Docker 服务..."

    try {
        # 检查 Docker 是否可用
        $dockerVersion = docker --version 2>$null
        if ($dockerVersion) {
            Write-Info "检测到 Docker，正在停止容器..."

            # 停止容器
            docker-compose down 2>$null

            # 可选：删除容器和镜像
            if ($Force) {
                Write-Info "强制清理 Docker 资源..."
                docker-compose down --volumes --remove-orphans 2>$null
                docker system prune -f 2>$null
            }

            Write-Success "Docker 服务已停止"
        }
    } catch {
        Write-Verbose "Docker 不可用或未运行容器"
    }
}

# 主停止函数
function Stop-Main {
    try {
        # 停止各个服务的进程
        Write-Info "开始停止服务进程..."

        # 停止后端服务 (uvicorn)
        Stop-PortProcess 8000 "后端服务"

        # 停止前端服务 (node)
        Stop-PortProcess 3000 "前端服务"

        # 停止 Mock 服务 (python)
        Stop-PortProcess 5000 "Mock 服务"

        # 停止 Ollama 服务
        Stop-OllamaService

        # 停止可能的 Python 进程
        Stop-ServiceProcess "python" "Python"
        Stop-ServiceProcess "python3" "Python3"

        # 停止可能的 Node.js 进程
        Stop-ServiceProcess "node" "Node.js"
        Stop-ServiceProcess "npm" "NPM"

        # 停止 Docker 服务
        Stop-DockerServices

        # 清理资源
        Clean-Up

        Write-ColorOutput "" "Magenta"
        Write-Success "所有服务已停止"
        Write-ColorOutput "" "Magenta"

        # 显示停止的进程信息
        Write-Info "已停止的服务:"
        Write-Info "  - AI 智能客服后端服务 (端口 8000)"
        Write-Info "  - React 前端服务 (端口 3000)"
        Write-Info "  - 订单 Mock 服务 (端口 5000)"
        Write-Info "  - Ollama 服务 (端口 11434)"

        if ($Clean) {
            Write-Info "  - 临时文件和缓存已清理"
        }

        Write-ColorOutput "" "Magenta"
        Write-Info "如果仍有进程未停止，请手动结束相关进程或重启计算机"

    } catch {
        Write-Error "停止过程中出现错误: $_"
        Write-Info "请手动检查和停止相关进程"
        exit 1
    }
}

# 显示使用帮助
function Show-Help {
    Write-ColorOutput "AI 智能客服业务助理停止脚本" "Magenta"
    Write-ColorOutput "" "Magenta"
    Write-ColorOutput "用法:" "Cyan"
    Write-ColorOutput "  .\stop.ps1 [选项]" "White"
    Write-ColorOutput "" "Magenta"
    Write-ColorOutput "选项:" "Cyan"
    Write-ColorOutput "  -Force       强制停止进程" "White"
    Write-ColorOutput "  -Clean       清理临时文件和缓存" "White"
    Write-ColorOutput "  -Verbose     显示详细输出" "White"
    Write-ColorOutput "  -Help        显示此帮助信息" "White"
    Write-ColorOutput "" "Magenta"
    Write-ColorOutput "示例:" "Cyan"
    Write-ColorOutput "  .\stop.ps1 -Force -Clean          # 强制停止并清理" "White"
    Write-ColorOutput "  .\stop.ps1 -Verbose               # 显示详细停止过程" "White"
}

# 检查是否请求帮助
if ($args -contains "-Help" -or $args -contains "--help" -or $args -contains "-h") {
    Show-Help
    exit 0
}

# 执行主函数
Stop-Main
